import json

import elasticapm
import tornado
from bugsnag.tornado import BugsnagRequestHandler

def json_to_dict(string):
    success = True
    try:
        result = json.loads(string)
    except Exception:
        result = dict(is_succ=False, error_msg="json字符串不合法")
        success = False
    return result, success

class BaseHandler(BugsnagRequestHandler):
    def initialize(self):
        pass

    @property
    def db(self):
        return self.application.db

    @property
    def db_slave(self):
        return self.application.db_slave

    @property
    def db_crm_slave(self):
        return self.application.db_crm_slave

    def options(self, *args, **kwargs):
        self.set_status(204)
        self.finish()

    def get_client_ip(self):
        headers = self.request.headers
        x_forwarded_for = headers.get('X-Forwarded-For', '')
        proxy_client_ip = headers.get('Proxy-Client-IP', '')
        wl_proxy_client_ip = headers.get('WL-Proxy-Client-IP', '')
        http_client_ip = headers.get('HTTP_CLIENT_IP', '')
        invalid_tuple = ('', 'unknown')
        if x_forwarded_for not in invalid_tuple:
            ip = x_forwarded_for.split(',')[0]
        elif proxy_client_ip not in invalid_tuple:
            ip = proxy_client_ip
        elif wl_proxy_client_ip not in invalid_tuple:
            ip = wl_proxy_client_ip
        elif http_client_ip not in invalid_tuple:
            ip = http_client_ip
        else:
            ip = headers.get('X-Real-Ip', '')
        return ip

    def get_user_locale(self):
        user_locale = self.get_argument('lang', None)
        if user_locale == 'zh_CN':
            return tornado.locale.get('zh_CN')
        elif user_locale == 'zh_TW':
            return tornado.locale.get('zh_TW')
        elif user_locale == 'en_US':
            return tornado.locale.get('en_US')

    def json_response(self, data):
        if isinstance(data, dict):
            trace_id = elasticapm.get_trace_id()
            data["trace_id"] = trace_id
        return self.finish(json.dumps(data, ensure_ascii=False))

class TransferBaseHandler(BaseHandler):
    def prepare(self):
        super(TransferBaseHandler, self).prepare()
        if self.request.method in ("POST", "PUT"):
            self.post_data, success = json_to_dict(self.request.body)
            if not success:
                result = self.post_data
                return self.json_response(result)
        self.set_header('Content-type', 'application/json')